#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/13 15:20
# @Author  : 王凯
# @File    : zhejiang_illegal.py
# @Project : spider-man
import re

from apps.tax_illegal.tax_illegal.items import NetTaxIllegalProItem
from apps.tax_illegal.tax_illegal.spiders import BaseTaxIllegalSpider
from utils.tools import urlencode


class ZhejiangIllegalSpider(BaseTaxIllegalSpider):
    name: str = "zhejiang_illegal"
    province: str = "浙江"
    url: str = "https://zhejiang.chinatax.gov.cn/module/jslib/bulletin/bullenrightfortop.jsp"  # 取首页

    def start_requests(self):
        yield from self.etax_search(**{"etax_url": "https://etax.zhejiang.chinatax.gov.cn:8443"})
        yield self.Request(
            "https://zhejiang.chinatax.gov.cn/module/jslib/bulletin/bullenrightfortop.jsp", callback=self.parse
        )

    def parse(self, response, **kwargs):
        total_record = response.xpath("//script//text()").re_first(r"totalRecord:(\d+)")
        if total_record and int(total_record) >= 1:
            url = "https://zhejiang.chinatax.gov.cn/module/jslib/bulletin/ajaxfors.jsp"
            for page in range(0, int(total_record) // 10 + 2):
                params = {"startrecord": f"{page * 10 + 1}", "endrecord": f"{(page + 1) * 10}"}
                data = {
                    "tablename": "jcms_33",
                    "nsrmc": "",
                    "nsrsbh": "",
                    "zcdz": "",
                    "zzjgdm": "",
                    "fddbrmc": "",
                    "fddbrsfzhm": "",
                    "cwfzrmc": "",
                    "cwfzrsfzhm": "",
                    "legalRepresentativeName": "",
                    "legalRepresentativeCardNo": "",
                    "financialManagerName": "",
                    "financialManagerCardNo": "",
                }
                yield self.FormRequest(
                    url + "?" + urlencode(params), formdata=data, method="POST", callback=self.parse_detail
                )

    def parse_detail(self, response, **kwargs):
        url_list = re.findall(r"window.open\(\'(.*?)\'", response.text)
        for url in url_list:
            yield self.Request(url, callback=self.parse_detail_info)

    def parse_detail_info(self, response, **kwargs):
        item = NetTaxIllegalProItem()
        item.province = self.province

        info = []
        for i in response.xpath("//table//tr"):
            res = [i.xpath("string(.)").get().strip() for i in i.xpath(".//td")]
            if res:
                if len(res) != 2:
                    continue
                info.append(res)

        for k, *v in info:
            v = " ".join(v)
            if "纳税人名称" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.company_name = v
            if "纳税人识别号" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.taxpayer_id = v
            if "组织机构代码" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.org_code = v
            if "注册地址" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.address = v
            if "法定代表人或者负责人" in k:
                v = re.sub(r"\s*", "", v)
                item.legal_representative = v
            if "违法期间法人代表或者负责人姓名" in k:
                v = re.sub(r"(<.*?>.*<.*?>|\s*)", "", v, flags=re.S)
                v = " ".join(re.sub(r"(<!--.*?-->|<.*?>)", "", v, flags=re.S).split())
                item.illegal_legal_representative = v.strip("...")
            if "负有直接责任的财务人员姓名" in k:
                v = " ".join(re.sub(r"(<!--.*?-->|<.*?>)", "", v, flags=re.S).split())
                item.resp_financial = v
            if "实际责任人姓名" in k:
                v = " ".join(re.sub(r"(<!--.*?-->|<.*?>)", "", v, flags=re.S).split())
                item.resp_person = v
            if "负有直接责任的中介机构信息" in k:
                v = " ".join(re.sub(r"(<!--.*?-->|<.*?>)", "", v, flags=re.S).split()).replace("null", "")
                item.resp_intermediary = v
            if "主体违法性质" in k:
                item.illegal_status = v
            if "主要违法事" in k:
                v = re.sub(r"(<!--.*?-->|\s*|<.*?>)", "", v, flags=re.S)
                illegal_facts_src = re.sub(r"(<.*?>|\s*|“|”)", "", re.sub(r"(<!--.*?-->)", "", v))
                illegal_facts = re.findall(
                    r"(.*(?:主要存在|存在以下问题)(?:[^根]*?[。，;；])*)[^。]*?(?:根据|依照|依据)+", illegal_facts_src
                )
                illegal_facts = illegal_facts[0] if illegal_facts else ""
                if illegal_facts:
                    basis_and_punishment = illegal_facts_src.replace(illegal_facts, "")
                else:
                    illegal_facts = illegal_facts_src
                    basis_and_punishment = ""
                item.basis_and_punishment = basis_and_punishment
                item.illegal_facts = illegal_facts
        pub_date = response.xpath('//*[@name="PubDate"]/@content').get()
        item.year = pub_date[:10].replace("-", "")
        yield item


if __name__ == "__main__":

    from scrapy import cmdline

    cmdline.execute(argv=["scrapy", "crawl", "zhejiang_illegal"])
